const _doc = document
const _win = window
// eslint-disable-next-line no-undef
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  // 获取 cookies
  if (request.message === 'GET_HOSTCOOKIE') {
    sendResponse({
      host: _doc.location.host,
      cookie: _doc.cookie
    })
  }
  // 获取 冻结数据
  if (request.message === 'GET_FREEZEDATA') {
    const { key } = request.data
    const d = _win.localStorage.getItem(key)
    sendResponse(d || '')
  }
  // 设置 冻结数据
  if (request.message === 'SET_FREEZEDATA') {
    const { key, value } = request.data
    _win.localStorage.setItem(key, value)
    sendResponse()
  }
})

const LOCALSTORAGE_COOKIES_KEY = 'TOOLS_FREEZE_COOKIESLIST'
// 判断是否需要 冻结cookie
const host = _doc.location.host
let data = _win.localStorage.getItem(LOCALSTORAGE_COOKIES_KEY)
if (data) {
  data = JSON.parse(data)
  const i = data.find(i => i.host === host)
  if (i) {
    const _obj = {}
    const obj = {}
    _doc.cookie.split(';').forEach(i => {
      const _ = i.split('=')
      obj[_[0]] = _[1]
    })
    i.cookie.split(';').map(i => i.trim()).forEach(i => {
      const _ = i.split('=')
      if (obj[_[0]] && obj[_[0]] === _[1]) {
        delete _obj[_[0]]
      } else {
        _obj[_[0]] = _[1]
      }
    })
    for (let key in _obj) {
      _doc.cookie = `${key}=${_obj[key]}`
    }
  }
}
